package com.htht.smartschool.util.cmpp;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.htht.smartschool.util.http.HttpUtil;
import com.htht.smartschool.util.system.ConfigUtil;
import com.htht.smartschool.util.system.DateUtil;
import com.htht.smartschool.util.system.GsonUtils;

public class CmppUtil {
	public static boolean sendToCmpp(String content,List<Long> tos){
		try {
			int groupsend_count = Integer.parseInt(ConfigUtil.getProperty("cmpp","groupsend_count"));
			dealList(content,groupsend_count,tos);
			return true;
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        for (int i=begin; i<begin+count; i++) bs[i-begin] = src[i];
        return bs;
    }
	private static void sendMess(String content,Long to) throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		map.put("content", content);
		map.put("to", String.valueOf(to));
		Map<String,String> param = new HashMap<String,String>();
		param.put("param", GsonUtils.getInstance().toJson(map));
		System.out.println(DateUtil.getFormatDate(new Date())+"---"+GsonUtils.getInstance().toJson(map));
		HttpUtil.getInstance().doPost("http://120.25.0.124:8080/cmppweb/send.do", param);
	}
	private static void dealList(String content,int groupsend_count,List<Long> tos) throws Exception{
		//每40条一组进行发送
		if(tos.size() > 0){
			int length = tos.size() / groupsend_count;
			if(length > 0){
				for (int i = 1; i <= length; i++) {
					Thread.sleep(500);
					List<Long> list = tos.subList(groupsend_count*(i-1), groupsend_count*i-1);
					for (int j = 0; j < list.size(); j++) {
						sendMess(content,list.get(j));
					}
				}
				if(tos.size() > length*groupsend_count){
					Thread.sleep(500);
					int len = tos.size() - length*groupsend_count;
					for (int i = 0; i < len; i++) {
						sendMess(content,tos.get(length*groupsend_count+i));
					}
				}
			}else{
				for (int i = 0; i < tos.size(); i++) {
					sendMess(content,tos.get(i));
				}
			}
			
		}
	}
}
